/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by hjh on 2019/8/28.
 */

import { parseCSS2JSMap, parseMap } from './theme.parse';

// sf-vue-components 的安全皮肤名字叫 default，这里映射一下。。
let vueComponentThemeMap = {
    security: 'default'
};

function initTheme () {

    // 直接在路由上取 theme 参数值，方便调试
    let theme = location.hash.match(/theme=(\w+)/);

    // 没有的话就用代码中写死的
    theme = theme && theme[1] || window.SHARED.theme;

    let compTheme = vueComponentThemeMap[theme] || theme;

    // 动态加载组件库的样式和业务样式
    import(`@sxf/sf-vue-component/dist/theme/${compTheme}.css`)
        .then(() => { // todo: 保证这个时候读的 style 就是组件库的 css
            let styles = document.getElementsByTagName('style');
            let targetStyleDom = styles[styles.length - 1];
            document.head.insertBefore(targetStyleDom, styles[1]);
        });
    import(`./${theme}/${theme}.pcss`);

    // 动态读取业务样式并转换成全局变量，方便 js 代码中使用
    let importCSS = import(`!!raw-loader!./${theme}/${theme}.pcss`);
    let importThemeColor = import(`@sxf/sf-theme/dist/${theme}.esm.js`);

    Promise.all([
        importCSS,
        importThemeColor
    ]).then(res => {
        let [cssModule, themeColorModule] = res;
        let cssContent = cssModule.default;
        let themeColorMap = themeColorModule.default;
        let themeBusiMap = parseCSS2JSMap(cssContent);
        let themeMap = Object.assign(themeBusiMap, themeColorMap);

        window.theme = parseMap(themeMap);
    });
}

export default initTheme;
